//
//  AffairSearchView.m
//  GuangzhouWireless
//
//  Created by 泉 汉水 on 11-5-24.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "BookReadView2.h"
#import "CommonUtil.h"
#import "TextReaderController.h"
#import "BookConstants.h"
//#define kDocumentFolder [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] 


@implementation BookReadView2

@synthesize localBookItem;
@synthesize titleLabel;
@synthesize coverImageView;
@synthesize buyButton;
@synthesize parentObject;
@synthesize waitingView;
@synthesize deleteSelectedButton;
@synthesize bookDelete;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

-(void)initExtend:(BookItem *)bookItem {
    localBookItem = bookItem;
    
    /*
    NSOperationQueue *queue = [NSOperationQueue new];
    [queue setMaxConcurrentOperationCount:1];
    
    
    NSInvocationOperation *operation = [[NSInvocationOperation alloc] 
                                        initWithTarget:self
                                        selector:@selector(loadImage:) 
                                        object:[NSString stringWithFormat:@"http://221.232.130.117:8080/files/i120/%@", [bookItem bookIconSmall]]];
    [queue addOperation:operation]; 
    [operation release];
     */
    //如果图片在本地，则直接显示，否则从服务端下载图片再显示
    if([[NSFileManager defaultManager] fileExistsAtPath:[kDocumentFolder stringByAppendingPathComponent:[bookItem bookIconSmall]]]
       ){
        coverImageView.image = [UIImage imageWithContentsOfFile:[kDocumentFolder stringByAppendingPathComponent:[bookItem bookIconSmall]]];
    }else{//下载图片，并保存到本地
        [waitingView startAnimating];
        /*
        NSURL *url2=[NSURL URLWithString:
                     [NSString stringWithFormat:@"%@%@%@", kServerURL, kFilei120, [bookItem bookIconSmall]]];
        [url2 dumbDownloadWithDelegate:self Title:@"BookCoverImage" WithToFileName:[kDocumentFolder stringByAppendingPathComponent:[bookItem bookIconSmall]]];
         */
        //如果有网络的情况下，下载图片
        if([CommonUtil isConnected]){
            NSOperationQueue *queue = [NSOperationQueue new];
            [queue setMaxConcurrentOperationCount:1];
            NSInvocationOperation *operation = [[NSInvocationOperation alloc] 
                                                initWithTarget:self
                                                selector:@selector(loadImage:) 
                                                object:[NSString stringWithFormat:@"%@%@%@", kServerURL, kFilei120, [bookItem bookIconSmall]]];
            [waitingView startAnimating];
            [queue addOperation:operation]; 
            [operation release];
        }
    }
    
    titleLabel.text = [bookItem bookName];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

- (void)dealloc
{
    [titleLabel release];
    [coverImageView release];
    [buyButton release];
    [waitingView release];
    
    [deleteSelectedButton release];
    
    [localBookItem release];
    [super dealloc];
}

-(IBAction)readButtonClick:(id)sender {
    //NSString *filePath = [CommonUtil unZipData:[localBookItem book4PadResource] extName:[localBookItem book4PadResourceType]];
    NSString *fileName = @"";
    NSString *fileType = @"";
    if([localBookItem book4PhoneResourceType] != nil && ![[localBookItem book4PhoneResourceType] isEqualToString:@""]) {
        fileName = [[localBookItem book4PhoneResource] stringByDeletingPathExtension];
        fileName = [NSString stringWithFormat:@"%@.%@",fileName, [localBookItem book4PhoneResourceType]];
        fileType = [localBookItem book4PhoneResourceType];
    }else{
        fileName = [[localBookItem book4PadResource] stringByDeletingPathExtension];
        fileName = [NSString stringWithFormat:@"%@.%@",fileName, [localBookItem book4PadResourceType]];
        fileType = [localBookItem book4PadResourceType];
    }
    
    if([fileName isEqualToString:@""] || [fileType isEqualToString:@""]){
        return;
    }
    
    if([fileType isEqualToString:@"txt"]){
        /*
        TextViewerController *controller = [[TextViewerController alloc] 
                                            initWithNibName:@"TextViewerController" bundle:nil];
        controller.bookNameLabel.text = [localBookItem bookName];
        controller.bookNameLabel2.text = [localBookItem bookName];
        controller.bookId = [localBookItem bookId];
        controller.bookFileName = [kDocumentFolder stringByAppendingPathComponent:fileName];
        [controller initExtend];
        [parentObject presentModalViewController:controller animated:YES]; 
        [controller release];*/
        
        TextReaderController *controller = [[[TextReaderController alloc] init] autorelease];
        controller.bookId = [localBookItem bookId];
        controller.bookFileName = [kDocumentFolder stringByAppendingPathComponent:fileName];
        [controller initExtend];
        HubuAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
        [delegate.navigationController presentModalViewController:controller animated:YES];
    }else{
    
        ReaderDocument *document = [ReaderDocument unarchiveFromFileName:fileName];
        // Create a brand new ReaderDocument object the first time we run
        if (document == nil) {
            document = [[[ReaderDocument alloc] initWithFilePath:
                         [kDocumentFolder stringByAppendingPathComponent:fileName] 
                                                        password:nil] autorelease];
        }
        
        ReaderViewController *readerViewController = [[ReaderViewController alloc] initWithReaderDocument:document];
        readerViewController.title = [localBookItem bookName];
        readerViewController.bookId = [localBookItem bookId];
        readerViewController.delegate = self; // Set the ReaderViewController delegate to self
        readerViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
        readerViewController.modalPresentationStyle = UIModalPresentationFullScreen;
        
        HubuAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
        [delegate.hubuViewController presentModalViewController:readerViewController animated:YES];
        [readerViewController release]; // Release the ReaderViewController
    }
}


- (void)dismissReaderViewController:(ReaderViewController *)viewController {
    HubuAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
	[delegate.hubuViewController dismissModalViewControllerAnimated:YES];
}

-(void)loadImage:(NSString *)url {
    NSData* imageData = [[NSData alloc]initWithContentsOfURL:
                         [NSURL URLWithString:url]];
    [self writeToFile:imageData];
    coverImageView.image = [[UIImage alloc] initWithData:imageData];
    [imageData release];
}

-(void)writeToFile:(NSData *)data{
	NSString *filePath= [NSString stringWithFormat:@"%@/%@", kDocumentFolder, [localBookItem bookIconSmall]];
	if([[NSFileManager defaultManager] fileExistsAtPath:filePath] == NO){
		[[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
	}
	FILE *file = fopen([filePath UTF8String], [@"ab+" UTF8String]);
	if(file != NULL){
		fseek(file, 0, SEEK_END);
	}
	int readSize = [data length];
	fwrite((const void *)[data bytes], readSize, 1, file);
	fclose(file);
}

- (void) dumbDownloadManagerDataDownloadFinished: (NSString *) fileName {
    DBUtil *db = [[DBUtil alloc] init];
    [db openDB];
    [db updateBook:@"icon" key:[localBookItem bookId] value:@"1"];
    [db closeDB];
    [db release];
    
    if([[NSFileManager defaultManager] fileExistsAtPath:[kDocumentFolder stringByAppendingPathComponent:[localBookItem bookIconSmall]]]
       ){
        coverImageView.image = [UIImage imageWithContentsOfFile:[kDocumentFolder stringByAppendingPathComponent:[localBookItem bookIconSmall]]];
    }
    
    [waitingView stopAnimating];
}

- (void) dumbDownloadManagerDataDownloadFailed: (NSString *) reason {
	//NSLog(@"dumb download failed:%@", reason);
}


-(IBAction)deleteBookSelect:(id)sender {
    UIButton *b = (UIButton *)sender;
    if(!bookDelete){
        [b setImage:[UIImage imageNamed:@"book_delete_bg.png"] forState:UIControlStateNormal];
        bookDelete = TRUE;
    }else{
        [b setImage:nil forState:UIControlStateNormal];
        bookDelete = FALSE;
    }
}

@end
